package dao.impl;

import dao.i.UserInfoDao;
import entity.UserInfo;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;

public class UserInfoDaoImpl implements UserInfoDao {

    java.sql.Connection connection = helper.DataSource.getConnection();

    @Override
    public boolean insertUserInfo(UserInfo userInfo) {
        String sql = "insert into UserInfo(userName,passWord,nickName,level,head,sex,age)\n"
                + "values(?,?,?,?,?,?,?)";
        PreparedStatement preparedStatement = null;
        try {
            preparedStatement = connection.prepareStatement(sql);
            preparedStatement.setString(1, userInfo.getUserName());
            preparedStatement.setString(2, userInfo.getPassWord());
            preparedStatement.setString(3, userInfo.getNickName());
            preparedStatement.setInt(4, userInfo.getLevel());
            preparedStatement.setString(5, userInfo.getHead());
            preparedStatement.setString(6, userInfo.getSex());
            preparedStatement.setInt(7, userInfo.getAge());
            int num = preparedStatement.executeUpdate();
            return num == 1;

        } catch (Exception e) {
            e.printStackTrace();
            try {
                preparedStatement.close();
            } catch (Exception e2) {
                e2.printStackTrace();
            }
        }
        return false;
    }

    @Override
    public UserInfo selectUserInfoByUserName(String userName) {
        String sql = "select * from UserInfo where userName=?";
        PreparedStatement preparedStatement = null;
        try {
            //预编译SQL设置值
            preparedStatement = connection.prepareStatement(sql);
            preparedStatement.setString(1, userName);
            //提交查询
            ResultSet resultSet = preparedStatement.executeQuery();
            //获取结果并提取
            resultSet.next();
            int id = resultSet.getInt("id");
            String userName1 = resultSet.getString("userName");
            String nickName = resultSet.getString("nickName");
            String passWord = resultSet.getString("passWord");
            int level = resultSet.getInt("level");
            String head = resultSet.getString("head");
            String sex = resultSet.getString("sex");
            int age = resultSet.getInt("age");
            //返回
            UserInfo userInfo = new UserInfo(id, userName1, passWord, nickName, level, head, sex, age);
            return userInfo;

        } catch (SQLException e) {
            e.printStackTrace();
            try {
                preparedStatement.close();
            } catch (SQLException e2) {
                e2.printStackTrace();
            }
        }
        return null;
    }

}
